package com.imooc.distributedlock;

/**
 * @Description :
 * @Author : YTY
 * @Date : 2021-02-13 08:12
 */

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LockController {

    private final RedissonClient redissonClient;

    @GetMapping("/lock")
    public void lock() {

        RLock lock = redissonClient.getLock("lock");

        try {
            boolean grabLock = lock.tryLock();
            if (grabLock) {
                log.info("开始下单...");
                Thread.sleep(3000);
                lock.unlock();
            } else {
                log.info("遗憾未能下单");
            }
//            lock.lock(5, TimeUnit.SECONDS);
//            Thread.sleep(6666);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
